package com.joolun.common.utils;


import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

public class GeneratorUtils {
    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    /**
     * 验证码难度级别，Simple只包含数字，Medium包含数字和小写英文，Hard包含数字和大小写英文
     */
    public enum SecurityCodeLevel {
        Simple, Medium, Hard
    }

    ;

    // 字符集合(除去易混淆的数字0、数字1、字母l、字母o、字母O)
    private static final char[] CHAR_CODE = {'1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
            'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

    /**
     * 产生默认验证码，6位中等难度<br>
     * 调用此方法和调用getSecurityCode(6, SecurityCodeLevel.Medium, false)有一样的行为
     *
     * @return 验证码
     * @see #getSecurityCode(int, SecurityCodeLevel, boolean)
     */
    public static String getSecurityCode() {
        return getSecurityCode(6, SecurityCodeLevel.Hard, false);
    }

    /**
     * 获取验证码，指定长度、难度、是否允许重复字符
     *
     * @param length      长度
     * @param level       难度
     * @param isCanRepeat 是否允许重复字符
     * @return 验证码
     */
    public static String getSecurityCode(int length, SecurityCodeLevel level,
                                         boolean isCanRepeat) {
        // 随机抽取len个字符
        int len = length;
        char[] code;

        // 根据不同的难度截取字符数组
        switch (level) {
            case Simple: {
                code = Arrays.copyOfRange(CHAR_CODE, 0, 9);
                break;
            }
            case Medium: {
                code = Arrays.copyOfRange(CHAR_CODE, 0, 33);
                break;
            }
            case Hard: {
                code = Arrays.copyOfRange(CHAR_CODE, 0, CHAR_CODE.length);
                break;
            }
            default: {
                code = Arrays.copyOfRange(CHAR_CODE, 0, CHAR_CODE.length);
            }
        }

        // 字符集合长度
        int n = code.length;

        // 抛出运行时异常
        if (len > n && isCanRepeat == false) {
            throw new RuntimeException(String.format(
                    "调用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出现异常，"
                            + "当isCanRepeat为%3$s时，传入参数%1$s不能大于%4$s", len,
                    level, isCanRepeat, n));
        }
        // 存放抽取出来的字符
        char[] result = new char[len];
        // 判断能否出现重复的字符
        if (isCanRepeat) {
            for (int i = 0; i < result.length; i++) {
                // 索引 0 and n-1
                int r = (int) (Math.random() * n);

                // 将result中的第i个元素设置为codes[r]存放的数值
                result[i] = code[r];
            }
        } else {
            for (int i = 0; i < result.length; i++) {
                // 索引 0 and n-1
                int r = (int) (Math.random() * n);

                // 将result中的第i个元素设置为codes[r]存放的数值
                result[i] = code[r];

                // 必须确保不会再次抽取到那个字符，因为所有抽取的字符必须不相同。
                // 因此，这里用数组中的最后一个字符改写codes[r]，并将n减1
                code[r] = code[n - 1];
                n--;
            }
        }
        return String.valueOf(result);
    }

//    public static final String getUUID() {
//        int hashCodeV = UUID.randomUUID().toString().hashCode();
//        if (hashCodeV < 0) {
//            hashCodeV = -hashCodeV;
//        }
//        return String.format("%015d", hashCodeV);
//    }

    private static int orderIndex = 1;
    private static int flowIndex = 1;
    private static String orderLastPrefix = "";
    private static String flowLastDate = "";

    public static synchronized String orderNo() {//// TODO: 28/12/2016  集群部署的时候注意需要控制
        return orderNo("");
    }

    public static synchronized String orderNo(String prefixCode) {
        if (prefixCode == null) {
            prefixCode = "";
        }
        Date now = new Date();
        String prefix = sdf.format(now);
        if (prefix.equals(orderLastPrefix)) {
            orderIndex++;
        } else {
            orderLastPrefix = prefix;
            orderIndex = 1;
        }
        return prefixCode + prefix + String.format("%04d", orderIndex);
    }

    public static synchronized String flowNo() {
        return flowNo("");
    }

    public static synchronized String flowNo(String prefixCode) {//// TODO: 28/12/2016  集群部署的时候注意需要控制
        if (prefixCode == null) {
            prefixCode = "";
        }
        Date now = new Date();
        String prefix = sdf.format(now);
        if (prefix.equals(flowLastDate)) {
            flowIndex++;
        } else {
            flowLastDate = prefix;
            flowIndex = 1;
        }
        return prefixCode + prefix + String.format("%04d", flowIndex);
    }

    private static String FORMATOR1 = "%s%s";
    private static AtomicInteger UNIQUE_ID = new AtomicInteger(0);



    public static void main(String[] args) {
//        UUID uuid = UUID.randomUUID();
        for (int i = 0; i <10 ; i++) {
            String nickname = GeneratorUtils.getSecurityCode(6, SecurityCodeLevel.Hard, true);
            System.out.println(nickname);
        }
//        int hashCode = uuid.toString().hashCode();
//        System.out.println(compareVersion("2.0.0", "3.0.2") + "");
//        System.out.println(String.format("%015d", hashCode));
//        String version = "1.0.0";
//        String[] array = version.split("\\.");
//        int v1 = Integer.valueOf(array[2]);
//        System.out.println("" + v1);
    }

    public static String getUUIDWithoutSplit() {
        String s = UUID.randomUUID().toString();
        // 去掉“-”符号
        return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
    }

//    public static List<String> getUUID(int number) {
//        if (number < 1) {
//            return null;
//        }
//        List<String> list = new ArrayList<>(number);
//        for (int i = 0; i < number; i++) {
//            list.add(getUUID());
//        }
//        return list;
//    }


    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * (获取指定长度uuid)
     *
     * @return
     */
    public static String getUUID(int len) {
        if (0 >= len) {
            return null;
        }

        String uuid = getUUID();
//        System.out.println(uuid);
        StringBuffer str = new StringBuffer();

        for (int i = 0; i < len; i++) {
            str.append(uuid.charAt(i));
        }

        return str.toString();
    }
}
